package main

import (
	"encoding/json"
	"fmt"
	"gitee.com/ichub/gofactroy/common/ichubbase"
	"gitee.com/ichub/gofactroy/nats/msg2nets"
	"github.com/nats-io/nats.go"

	"log"
	"time"
)

var Nc *nats.Conn

// 邀请码注册消息主题
const SubjReg = "UserRegMsg2Cms"
const Nats_URL = "nats://192.168.4.111:4222"
const SubjOrder = "OrderFinishMsg2Cms"

// AdCode
type OrderFinishMsg2Cms struct {
	//广告码
	Code string
	//用户id
	UserId int64
	//订单标识
	OrderId, OrderLineId string

	//订单完成时间 s
	FinishedTime int64
}

// 前端链接注册，header增加邀请码 InviteCode
type UserRegMsg2Cms struct {
	//邀请注册
	//邀请码
	InviteCode string
	//用户id
	UserId int64
	//注册时间 s
	RegTime int64
}

func (entity *UserRegMsg2Cms) String() string {
	s, err := json.Marshal(entity)
	if err != nil {
		fmt.Println(err.Error())
		return "{}"
	}
	return string(s)

}
func (entity *UserRegMsg2Cms) Unmarshal(body string) error {
	return json.Unmarshal([]byte(body), entity)

}
func (entity *UserRegMsg2Cms) ToString() string {
	s, err := json.MarshalIndent(entity, "", " ")
	if err != nil {
		fmt.Println(err.Error())
		return "{}"
	}
	return string(s)

}

func (entity *UserRegMsg2Cms) RegReplyHandler(m *nats.Msg) {
	fmt.Printf("Received a message: %s\n", string(m.Data))
	resmsg := msg2nats.NatsMessage{}
	err := resmsg.Unmarshal(string(m.Data))
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("接收了邀请码注册消息：" + resmsg.Header.ToString())
	if resmsg.Body != nil {
		fmt.Println(string(*resmsg.Body))
	}
}

func roachDBUrlConnPG() string {
	return "postgresql://root@192.168.4.119:26257/" + ichubbase.MODULE_MAP[ichubbase.APP].DBNAME + "?sslmode=disable"

}

var natsManager msg2nats.NatsManager

func main() {

	//tabletool := &dbtool.TableTool{
	//	Dbtype_mysql: false,
	//	Db:            ichubbase.MODULE_MAP[ichubbase.APP].DBNAME,
	//	Table:        "employee",
	//	Author:       "leijianming",
	//	ModuleName:   ichubbase.MODULE_MAP[ichubbase.APP], //MODULE_NAME,
	//}
	//
	//dBUrl := roachDBUrlConnPG()
	//var dbinst *gorm.DB = tabletool.InitDb(dBUrl)
	//defer dbinst.Close()
	//nats.DefaultURL
	nc, err := nats.Connect(Nats_URL)
	Nc = nc

	if err != nil {
		log.Fatal(err)
	}
	defer Nc.Close()

	natsMessage := msg2nats.NatsMessage{}
	natsMessage.Header.Topic = SubjReg
	natsMessage.Header.Version = "V1"
	regMsg := UserRegMsg2Cms{}

	natsManager = msg2nats.NatsManager{
		Nc: Nc,
	}
	err = natsManager.Subscribe(SubjReg)
	if err != nil {
		fmt.Println(err)
		return
	}

	regMsg.InviteCode = "A31234"
	regMsg.RegTime = time.Now().Unix()
	regMsg.UserId = -1111
	natsMessage.IniData([]byte(regMsg.String()))

	err = natsManager.Publish(natsMessage)
	err = natsManager.Publish(natsMessage)
	regMsg = UserRegMsg2Cms{}
	regMsg.InviteCode = "A2"
	regMsg.RegTime = time.Now().Unix()
	regMsg.UserId = 22
	natsMessage.IniData([]byte(regMsg.String()))
	err = natsManager.Publish(natsMessage)
	if err != nil {
		fmt.Println(err)
		return
	}
	err = natsManager.Publish(natsMessage)
	time.Sleep(1e7)

}
